<template>
  <div>
    <div class="relative mb-2 text-center leading-8">
      <strong>{{ rootDepartment.name }}</strong>
      <!-- 修改点击事件，传入空对象 -->
      <el-icons class="!absolute right-0 top-1/2 -translate-y-1/2 cursor-pointer hover:!text-action" name="CirclePlus"
        @click="onAdd()" />
    </div>
    <el-tree ref="treeRef" :key="treeKey"
      :props="{ children: 'children', label: 'name', isLeaf: (data) => !data.is_has_child }" :load="getDeptData" lazy
      @node-click="handleNodeClick" node-key="department_id">
      <template #default="{ node, data }">
        <div class="flex justify-between w-full">
          <div class="w-full">{{ node.label }}</div>
          <div>
            <!-- 修改 @command 事件，手动传递 data -->
            <el-dropdown @command="handleCommand($event, data)" placement="bottom">
              <el-icons name="MoreFilled" class="cursor-pointer hover:!text-action" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete">删除部门</el-dropdown-item>
                  <el-dropdown-item command="edit">修改部门</el-dropdown-item>
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
    </el-tree>

    <el-dialog v-model="showDeptFormDialog" :title="info ? '修改部门' : '添加部门'" width="50%" destroy-on-close>
      <ConfigForm :info="info" rawKey="department_id" :server="departmentServer" :configs="createForm"
        :beforeSubmit="beforeSubmit" @success="onSuccessForm" @close="showDeptFormDialog = false" />
    </el-dialog>
  </div>
</template>

<script setup>
import { departmentServer } from '@/api'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // 引入 ElMessageBox
import ConfigForm from '@/components/CRUD/ConfigForm.vue'
import OrganizationDialog from '@/components/Organization/OrganizationDialog.vue'
import { useUserStore } from '@/stores/user'
// 定义 emits
const emit = defineEmits(['node-clicked'])

const userStore = useUserStore() // 获取用户信息
const rootDepartment = { // 根部门
  department_id: userStore.departmentId,
  name: userStore.departmentName,
}

const treeKey = ref(1); // 用于强制刷新树组件
const treeRef = ref(null) // 获取树组件的引用

const getDeptData = async (node, resolve, reject) => {
  let pid, pName;
  if (node.level === 0) {
    pid = rootDepartment.department_id
    pName = rootDepartment.name
  } else {
    pid = node.data.department_id
    pName = node.data.name
  }
  try {
    const { data } = await departmentServer.get({ pid });
    const list = data || [];
    list.forEach(v => {
      v.parent = { // 处理上级部门数据
        department_id: pid,
        name: pName,
      }
      v.leader = { // 处理负责人数据
        user_id: v.leader_id,
        name: v.leader_name,
      }
    })
    resolve(list)
  } catch (error) {
    console.error('获取部门数据失败:', error)
    reject(error)
  }
}

// 处理下拉菜单命令
const handleCommand = (command, data) => {
  switch (command) {
    case 'delete':
      onDelete(data)
      break
    case 'edit':
      onEdit(data)
      break
    case 'add':
      onAdd(data)
      break
  }
}
// 点击部门，查询部门人员
const handleNodeClick = (data) => {
  // 触发 node-clicked 事件并传递节点数据
  emit('node-clicked', data)
}

const createForm = [
  {
    label: '上级部门',
    key: 'parent',
    type: 'custom',
    required: true,
    props: {
      type: 'department',
      placeholder: '请选择上级部门',
    },
    render: OrganizationDialog,
  },
  {
    label: '名称',
    key: 'name',
    type: 'input',
    required: true,
    props: {
      placeholder: '请输入部门名称',
    },
  },
  {
    label: '负责人',
    key: 'leader',
    type: 'custom',
    required: true,
    props: {
      type: 'user',
      placeholder: '请输入负责人',
    },
    render: OrganizationDialog,
  },
]

// 添加or修改部门弹窗
const showDeptFormDialog = ref(false)
// 表单默认数据
const info = ref(null)
// 添加部门
const onAdd = (data) => {
  showDeptFormDialog.value = true
  info.value = null;
  const parentConfig = createForm.find(item => item.key === 'parent');
  if (data) {
    parentConfig.props.disabled = true; // 禁用上级部门选择
    parentConfig.defaultValue = { // 设置默认值
      department_id: data.department_id,
      name: data.name,
    };
  } else {
    parentConfig.props.disabled = false; // 否则启用
    parentConfig.defaultValue = null;
  }
}
// 修改部门
const onEdit = (item) => {
  showDeptFormDialog.value = true
  info.value = item;
}
// 删除部门
const onDelete = async (data) => {
  await ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await departmentServer.delete({ id: data.department_id });
  ElMessage.success('删除成功');
  refreshTreeNode(data.pid);
}

// 提交表单前的处理
const beforeSubmit = (params) => {
  // 处理上级部门的值
  if (params.parent) {
    params.pid = params.parent.department_id
    delete params.parent
  }
  // 处理负责人
  if (params.leader) {
    params.leader_id = params.leader.user_id
    delete params.leader
  }
  return params
}
const onSuccessForm = (_, { params }) => {
  refreshTreeNode(params.pid)
}

const refreshTreeNode = (nodeKey) => {
  const pNode = treeRef.value.getNode(nodeKey);
  if (pNode) {
    pNode.loaded = false
    pNode.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
  } else {
    treeKey.value += 1; // 强制刷新树组件
  }
}
</script>
